"use client";
import { Button, Card, Flex, message, Typography } from "antd";
import "./index.css";
import Title from "antd/es/typography/Title";
import TagList from "@/components/TagList";
import MdViewer from "@/components/MdViewer";
import useAddUserSignInRecord from "@/hooks/useAddUserSignInRecord";
import React, { useEffect, useState } from "react";
import { StarFilled, StarOutlined } from "@ant-design/icons";
import { addCollectionPost, getCollectionPost } from "@/api/WishController";
import useAddUserSignInQuestion from "@/hooks/useAddUserSignInQuestion";
import { getQuestionAiByUsingGet } from "@/api/questionController";
import { Bubble, BubbleProps } from "@ant-design/x";
import markdownit from "markdown-it";
import { useSelector } from "react-redux";
import { RootState } from "@/stores";
import AccessEnum from "@/access/accessEnum";
import {
  addUserSignInQuestionPost,
  addUserSignInUsingPost,
} from "@/api/userController";

interface Props {
  question: API.QuestionVO;
}

/**
 * 题目卡片组件
 * @param props
 * @constructor
 */
const QuestionCard = (props: Props) => {
  const { question } = props;
  const [showAnswer, setShowAnswer] = useState(false);
  const [showIcon, setShowIcon] = useState(false);
  const [AiContent, seAiContent] = useState();
  const loginUser = useSelector((state: RootState) => state.loginUser);

  // 只在用戶已登錄時執行簽到
  useEffect(() => {
    const handleSignIn = async () => {
      if (loginUser.userRole !== AccessEnum.NOT_LOGIN) {
        try {
          // 調用普通簽到
          await addUserSignInUsingPost();
          // 調用問題簽到
          await addUserSignInQuestionPost({
            questionId: question.id,
          });
        } catch (error) {
          console.error("簽到失敗:", error);
        }
      }
    };
    handleSignIn();
  }, [loginUser.userRole, question.id]);

  //收藏;
  const WishCollections = async () => {
    if (loginUser.userRole === AccessEnum.NOT_LOGIN) {
      message.warning("請先登錄後再收藏");
      return;
    }
    const res = await addCollectionPost({
      questionId: question.id,
    });
    try {
      // @ts-ignore
      if (res.data == true) {
        setShowIcon(true);
        message.success("收藏成功");
      } else {
        setShowIcon(false);
        message.success("取消收藏");
      }
    } catch (e) {
      // @ts-ignore
      message.error("收藏失败，" + e.message);
    }
  };

  useEffect(() => {
    // 定義異步獲取數據的函數
    const fetchData = async () => {
      // 獲取 AI 內容，與用戶登錄狀態無關
      const aiContent = await getQuestionAiByUsingGet({
        questionId: question.id,
      });

      if (aiContent.data == null) {
        // @ts-ignore
        seAiContent(null);
      }
      console.log(aiContent);
      // @ts-ignore
      seAiContent(aiContent.data);

      // 只在用戶已登錄時獲取收藏狀態
      if (loginUser.userRole !== AccessEnum.NOT_LOGIN) {
        const res = await getCollectionPost({
          questionId: question.id,
        });
        try {
          // @ts-ignore
          if (res.data == true) {
            setShowIcon(true);
          } else {
            setShowIcon(false);
          }
        } catch (err) {
        } finally {
        }
      }
    };

    // 立即執行數據獲取
    fetchData();

    // 可選：清理函數（用於取消請求）
    return () => {};
  }, [loginUser.userRole]);

  const md = markdownit({ html: true, breaks: true });
  const renderMarkdown: BubbleProps["messageRender"] = (content) => (
    <Typography>
      {/* biome-ignore lint/security/noDangerouslySetInnerHtml: used in demo */}
      <div dangerouslySetInnerHTML={{ __html: md.render(content) }} />
    </Typography>
  );

  return (
    <div className="question-card">
      <Card>
        <Title level={1}>{question.title}</Title>
        <TagList tagList={question.tagList} />
        <div style={{ marginBottom: 16 }} />
        <MdViewer value={question.content} />
        <div style={{ marginBottom: 16 }} />
        <Flex gap={16}>
          <Button onClick={() => setShowAnswer(!showAnswer)}>
            {showAnswer ? "隱藏答案" : "查看答案"}
          </Button>
          {loginUser.userRole !== AccessEnum.NOT_LOGIN && (
            <div style={{ marginLeft: 20 }}>
              <Button
                shape="circle"
                size="large"
                icon={
                  showIcon ? (
                    <StarFilled style={{ fontSize: 30, color: "#ff6800" }} />
                  ) : (
                    <StarOutlined style={{ fontSize: 30 }} />
                  )
                }
                style={{ border: "none", boxShadow: "none" }}
                onClick={WishCollections}
              />
            </div>
          )}
        </Flex>
      </Card>
      {showAnswer && (
        <div>
          <Card title="推荐答案" style={{ marginTop: 16 }}>
            <div style={{ marginBottom: 16 }} />
            <MdViewer value={question.answer} />
          </Card>
        </div>
      )}
      <div style={{ marginTop: 10 }}>
        <Card title="面试鸭的建议">
          <Bubble
            typing
            content={AiContent}
            messageRender={renderMarkdown}
            styles={{ content: { backgroundColor: "#fff" } }}
          />
        </Card>
      </div>
    </div>
  );
};

export default QuestionCard;
